// vk.com - task 5
// Dictionary lookup
// main.c

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include "lookup.h"

#define THREADS_ENABLED 10
#define CONST_BLOCK_SIZE 65536	//64kb


int main(int argc, char *argv[]) {
char the_filename[255];
char the_substring[255];
FILE *dict_file;
time_t start_time, end_time;
int i;
int thread_id[THREADS_ENABLED];
int thread_result;
pthread_t thread[THREADS_ENABLED];

	
	if (argc-1 == 0) {
		printf("Error: No file name specified.\n");
		return 1;
	}
	strcpy(the_filename, argv[1]);
	dict_file = fopen(the_filename, "r");
	if (dict_file == NULL) {
		printf("Error: Unable to open the file.\n");
		return 2;
	}
	fclose(dict_file);


	Lookup_SetBlockSize(CONST_BLOCK_SIZE);	// For the future possibility to set the BlockSize as command line argument
	Lookup_SetDictFilename(the_filename);
	printf("The file is available. Please input the string to search or type 'exit'.\n");


	while (1) {
		printf("> ");
		fflush(stdin);
		fgets(the_substring, sizeof(the_substring), stdin);
		the_substring[strlen(the_substring)-1] = '\0';
		if (!strcmp(the_substring, "exit")) break;

		Lookup_Reset();
		Lookup_SetSubstring(the_substring);
		
		
		start_time = time(NULL);
		for (i=0; i<THREADS_ENABLED; i++) {
			thread_id[i] = i;
			thread_result = pthread_create(&thread[i], NULL, Lookup_Thread, &thread_id[i]);
			if (thread_result) {
				printf("Error: Failed to create threads");
				return 3;
			}
		}
		for (i=0; i<THREADS_ENABLED; i++) {
			thread_result = pthread_join(thread[i], NULL);
			if (thread_result) {
				printf("Error: Failed to join threads");
				return 4;
			}			
		}
		end_time = time(NULL);


		if (Lookup_IsSuccessful()) printf("YES"); else printf("NO");
		printf("   : Search time: %f sec.\n", difftime(end_time, start_time));
	}
		
	return 0;
}
